import * as electron from 'electron'
import path from 'path'
import { fileURLToPath } from 'url'

const { app, BrowserWindow, ipcMain, dialog } = electron.default || electron

const __dirname = path.dirname(fileURLToPath(import.meta.url))

let mainWindow

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
      sandbox: false,
      nodeIntegration: false,
      contextIsolation: true,
      webviewTag: true
    },
    useContentSize: true,
    minWidth: 1200,
    minHeight: 800,
    resizable: true,
    autoHideMenuBar: true
  })

  // 调整页面尺寸和滚动条
  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.insertCSS(`
      ::-webkit-scrollbar {
        display: none;
      }
      html, body {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
        overflow: hidden;
      }
      #app {
        width: 100%;
        height: 100%;
      }
    `)
  })

  // 开发环境下加载Vite开发服务器
  if (process.env.NODE_ENV === 'development') {
    const devUrl = 'http://localhost:5173/'
    console.log('Loading development URL:', devUrl)
    mainWindow.loadURL(devUrl)
    mainWindow.webContents.on('did-fail-load', () => {
      console.error('Failed to load development server, retrying...')
      setTimeout(() => mainWindow.loadURL(devUrl), 1000)
    })
    mainWindow.webContents.openDevTools()
    mainWindow.webContents.session.clearCache()
    mainWindow.webContents.reloadIgnoringCache()
  } else {
    // 生产环境下加载打包后的文件
    mainWindow.loadFile(path.join(__dirname, 'dist/index.html'))
  }

  mainWindow.on('closed', () => {
    mainWindow = null
  })
}

app.whenReady().then(() => {
  createWindow()
  
  // 处理文件夹选择请求
  ipcMain.handle('select-folder', async () => {
    const result = await dialog.showOpenDialog({
      properties: ['openDirectory']
    })
    return result.filePaths[0] || null
  })
  
  // 处理对话框打开请求
  ipcMain.handle('show-open-dialog', async (event, options) => {
    const result = await dialog.showOpenDialog(options)
    return result
  })
  
  // 处理读取目录请求
  ipcMain.handle('read-dir', async (event, path) => {
    const fs = await import('fs/promises')
    try {
      const files = await fs.readdir(path)
      return files
    } catch (err) {
      console.error('Error reading directory:', err)
      return []
    }
  }),
  
  // 处理读取文件请求
  ipcMain.handle('read-file', async (event, { path, encoding }) => {
    const fs = await import('fs/promises')
    try {
      const options = encoding ? { encoding: null } : { encoding: 'utf-8' }
      const content = await fs.readFile(path, options)
      return encoding === 'binary' ? content.buffer : content
    } catch (err) {
      console.error('Error reading file:', err)
      return null
    }
  }),
  
  // 处理在文件管理器中显示文件请求
  ipcMain.handle('show-item-in-folder', async (event, path) => {
    try {
      const { shell } = electron.default || electron
      shell.showItemInFolder(path)
      return true
    } catch (err) {
      console.error('Error showing item in folder:', err)
      return false
    }
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (mainWindow === null) {
    createWindow()
  }
})